{
 "cells": [
  {
   "cell_type": "code",
   "id": "initial_id",
   "metadata": {
    "collapsed": true
   },
   "source": [
    "import torch\n",
    "import torchvision\n",
    "from torch import nn\n",
    "from torch.utils.data import DataLoader\n",
    "\n",
    "from d2l import torch as d2l\n",
    "\n",
    "# 1. 加载数据\n",
    "train_iter = torchvision.datasets.FashionMNIST(\n",
    "    root=\"../data\",\n",
    "    train=True,\n",
    "    transform=torchvision.transforms.ToTensor(),\n",
    "    download=True,\n",
    ")\n",
    "\n",
    "test_iter = torchvision.datasets.FashionMNIST(\n",
    "    root=\"../data\",\n",
    "    train=False,\n",
    "    transform=torchvision.transforms.ToTensor(),\n",
    "    download=True,\n",
    ")\n",
    "\n",
    "# 2. 利用DataLoader加载数据集\n",
    "batch_size = 256\n",
    "dataloader_workers = 4\n",
    "train_iter = DataLoader(train_iter, batch_size, shuffle=True, num_workers=dataloader_workers)\n",
    "test_iter = DataLoader(test_iter, batch_size, shuffle=False, num_workers=dataloader_workers)\n",
    "\n",
    "# 3. 搭建隐藏层：只有一层隐藏层，包含256个隐藏单元\n",
    "num_inputs, num_outputs, num_hiddens = 28 * 28, 10, 256\n",
    "W1 = nn.Parameter(torch.randn(num_inputs, num_hiddens, requires_grad=True))  # 第一层weight\n",
    "b1 = nn.Parameter(torch.zeros(num_hiddens, requires_grad=True))  # 第一层bias\n",
    "W2 = nn.Parameter(torch.randn(num_hiddens, num_outputs, requires_grad=True))  # 第二层/输出层weight\n",
    "b2 = nn.Parameter(torch.zeros(num_outputs, requires_grad=True))  # 第二层/输出层bias\n",
    "params = [W1, b1, W2, b2]\n",
    "\n",
    "\n",
    "# 4. ReLU激活函数，自己定义\n",
    "def relu(x):\n",
    "    a = torch.zeros_like(x)\n",
    "    return torch.max(x, a)\n",
    "\n",
    "\n",
    "# 5. 完全手搭模型nn\n",
    "def net(X):\n",
    "    X = X.reshape((-1, num_inputs))\n",
    "    H = relu(X @ W1 + b1)  # @ <=> dot\n",
    "    return (H @ W2 + b2)\n",
    "\n",
    "\n",
    "# 6. 损失函数\n",
    "loss = nn.CrossEntropyLoss(reduction='none')\n",
    "\n",
    "# 7. 开始训练\n",
    "num_epochs, lr = 10, 0.1\n",
    "updater = torch.optim.SGD(params, lr=lr)  # 优化器\n",
    "d2l.train_ch3(net, train_iter, test_iter, loss, num_epochs, updater)  # 仅仅用于画图"
   ],
   "execution_count": 3,
   "outputs": []
  },
  {
   "metadata": {},
   "cell_type": "code",
   "execution_count": null,
   "source": "",
   "id": "f46e94c0becc715f",
   "outputs": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
